package yto.freemarker.bootrocketmq.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 如果项目中不需要用到多组不同的的MQ，则不需要此类
 *
 * @author dongxing
 */

@Component
@Slf4j
public class RocketMQOtherTemplate implements InitializingBean, DisposableBean {

    @Value("${spring.rocketmq.other.nameServer}")
    private String otherNameServer;

    @Value("${spring.rocketmq.other.producer.group}")
    private String otherGroup;

    @Getter
    @Setter
    private DefaultMQProducer producer;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("Initializing other rocketmq: otherNameServer:" + otherNameServer);
        producer = new DefaultMQProducer();
        producer.setNamesrvAddr(otherNameServer);
        producer.setProducerGroup(otherGroup);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));
        producer.start();
    }

    @Override
    public void destroy() throws Exception {
        Optional.ofNullable(producer).ifPresent(p -> p.shutdown());
    }

}
